package com.test.template.test_v.hello;

import com.test.template.tpo.Person;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.junit.Test;

import java.io.*;

public class VelocityExample {

    static String generatePath = "src/test/java/com/test/template/generate";


    private static VelocityEngine getVelocityEngine() {
        // 初始化 Velocity 引擎
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.setProperty("file.resource.loader.path", "src/test/resources/templates");
        velocityEngine.init();
        return velocityEngine;
    }

    public static void main(String[] args) {
        VelocityEngine velocityEngine = getVelocityEngine();

        // 加载模板
        Template template = velocityEngine.getTemplate("hello.vm");

        // 设置上下文变量
        VelocityContext context = new VelocityContext();
        context.put("name", "Alice");
        context.put("location", "Wonderland");

        // 渲染模板
        StringWriter writer = new StringWriter();
        template.merge(context, writer);

        // 输出结果
        System.out.println(writer.toString());
    }


    @Test
    public void person() {
        VelocityEngine velocityEngine = getVelocityEngine();

        // 加载模板
        Template template = velocityEngine.getTemplate("person.vm");

        // 设置上下文变量
        VelocityContext context = new VelocityContext();

        Person person = new Person();
        person.setName("Alice");
        person.setAge(18);

        context.put("person", person);

        // 渲染模板
        StringWriter writer = new StringWriter();
        template.merge(context, writer);

        // 输出结果
        System.out.println(writer.toString());

        try (
                FileOutputStream fos = new FileOutputStream(new File(generatePath + "/test.html"));
        ) {
            fos.write(writer.toString().getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
